package cz.vutbr.fit.xzemko01.tfmcbs.validation.validators;

import java.util.Map;

import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.DiagnosticChain;

import cz.vutbr.fit.xzemko01.tfmcbs.model.Component;
import cz.vutbr.fit.xzemko01.tfmcbs.model.Entity;

import cz.vutbr.fit.xzemko01.tfmcbs.validation.utils.DiagnosticBuilder;

public final class ComponentValidator implements Validator<Component> {
	
	private static ComponentValidator componentValidator;
	
	private Validator<Entity> entityValidator;
	
	private ComponentValidator() {
		entityValidator = EntityValidator.getInstance();
	}
	
	public static Validator<Component> getInstance() {
		if(componentValidator == null) {
			componentValidator = new ComponentValidator();
		}
		return componentValidator;
	}
	
	@Override
	public boolean validate(Component component, DiagnosticChain diagnostics, Map<Object, Object> context) {
		boolean result = entityValidator.validate(component, diagnostics, context);
		result &= validateComponentStereotypeNotEmpty(component, diagnostics, context);
		result &= validateComponentNameFirstLetterIsUpperCase(component, diagnostics, context);
		return result;
	}

	private boolean validateComponentStereotypeNotEmpty(Component component, DiagnosticChain diagnostics, Map<Object, Object> context) {
		String stereoType = component.getStereotype();
		boolean result = true;

		if (stereoType == null || stereoType.trim().isEmpty()) {
			String errorMessage = "Component's \"" + component.getName() + "\" stereotype is empty.";
			Diagnostic diagnostic = new DiagnosticBuilder(component)
											.setMessage(errorMessage).build();
			diagnostics.add(diagnostic);
			result = false;
		}
		return result;
	}
	
	private boolean validateComponentNameFirstLetterIsUpperCase(Component component, DiagnosticChain diagnostics, Map<Object, Object> context) {
		String name = component.getName();
		if(name == null || name.trim().isEmpty()) {
			return true;
		}
		
		boolean result = true;
		
		char firstLetter = name.charAt(0);
		boolean isUpperCaseChar = firstLetter >= 'A' && firstLetter <= 'Z';
		if (!isUpperCaseChar) {
			String errorMessage = "Component's name \"" + component.getName() + 
					"\" should begin with upper case letter.";
			Diagnostic diagnostic = new DiagnosticBuilder(component)
										.setSeverity(Diagnostic.WARNING)
										.setMessage(errorMessage).build();
			diagnostics.add(diagnostic);
			result = false;
		}
		return result;
	}
}
